using System;
using System.Collections;
using DailyReport.Core.Data.Dao;
using DailyReport.Core.Data.Model;
using log4net;
using NHibernate;
using NHibernate.Expression;

namespace DailyReport.NHibernateDao.Data.Dao
{
    public class TimeRegisterDao : NHibernateBaseDao<TimeRegister, int>, ITeamRegisterDao
    {
        //public IList getTimeRegistersList(int userId, string sortExpression, int maxRows, int startRowIndex)
        ILog log = LogManager.GetLogger("TimeRegisterDao");
        public IList getTimeRegistersList(int userId, string sortExpression)
        {
            log.Debug("getTimeRegistersList");
            ICriteria criteria = session.CreateCriteria(typeof(TimeRegister));

            if (sortExpression != null && sortExpression.Length > 0)
                criteria.AddOrder(Order.Asc(sortExpression));

            criteria.CreateCriteria("Daily", "d").Add(Expression.Eq("d.Current", true));
            return criteria.List();
        }
        
        
        public int getTimeRegisterCount(int userId)
        {
            //IQuery query = session.CreateQuery("select count(ID) from " + typeof(TimeRegister) + " t, t.Daily d Where d.Current = true and t.User.ID = :userId");
            IQuery query = session.CreateQuery("select count(ID) from TimeRegister t, t.Daily d Where d.Current = true and t.User.ID = :userId");
            query.SetInt32("userId", userId);
            return (int)query.UniqueResult();
        }

        public TimeRegister getCurrentActiveRegister(int userId)
        {
            log.Debug("getCurrentActiveRegister...");
            IQuery query =
                session.CreateQuery("from TimeRegister a where a.Daily.User.ID = :userId and a.EndTime is null");
            query.SetInt32("userId", userId);
            TimeRegister result = (TimeRegister) query.UniqueResult();
            log.Debug("Result:"+result);
            log.Debug("After getCurrentRegister.....");
            return result;
        }
    }
}